package com.example.hrsystem.ui.task;

import android.app.Application;
import android.os.AsyncTask;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.hrsystem.data.model.TaskItem;
import com.example.hrsystem.data.repository.TaskRepository;

import java.util.Date;
import java.util.List;

/**
 * 任务ViewModel
 * 连接Repository和UI层，处理待办/待阅事项相关的UI数据逻辑
 */
public class TaskViewModel extends AndroidViewModel {

    private TaskRepository repository;
    private LiveData<List<TaskItem>> allTasks;
    private MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);
    private MutableLiveData<String> errorMessage = new MutableLiveData<>();

    /**
     * 构造方法
     */
    public TaskViewModel(@NonNull Application application) {
        super(application);
        repository = new TaskRepository(application);
        allTasks = repository.getAllTasks();
    }

    /**
     * 获取所有任务
     */
    public LiveData<List<TaskItem>> getAllTasks() {
        return allTasks;
    }

    /**
     * 根据任务类型获取任务
     */
    public LiveData<List<TaskItem>> getTasksByType(String taskType) {
        return repository.getTasksByType(taskType);
    }

    /**
     * 根据任务状态获取任务
     */
    public LiveData<List<TaskItem>> getTasksByStatus(String status) {
        return repository.getTasksByStatus(status);
    }

    /**
     * 获取指定员工已完成任务数量
     */
    public LiveData<Integer> getDoneTaskCount(String employeeId) {
        return repository.getDoneTaskCount(employeeId);
    }

    /**
     * 根据优先级获取任务
     */
    public LiveData<List<TaskItem>> getTasksByPriority(String priority) {
        return repository.getTasksByPriority(priority);
    }

    /**
     * 根据接收者ID获取任务
     */
    public LiveData<List<TaskItem>> getTasksByAssigneeId(String assigneeId) {
        return repository.getTasksByAssigneeId(assigneeId);
    }

    /**
     * 根据创建者ID获取任务
     */
    public LiveData<List<TaskItem>> getTasksByCreatorId(String creatorId) {
        return repository.getTasksByCreatorId(creatorId);
    }

    /**
     * 根据ID获取任务详情
     */
    public LiveData<TaskItem> getTaskById(int taskId) {
        return repository.getTaskById(taskId);
    }

    /**
     * 获取待办事项总数
     */
    public LiveData<Integer> getTodoTaskCount(String assigneeId) {
        return repository.getTodoTaskCount(assigneeId);
    }

    /**
     * 获取待阅事项总数
     */
    public LiveData<Integer> getReadTaskCount(String assigneeId) {
        return repository.getReadTaskCount(assigneeId);
    }

    /**
     * 插入任务
     */
    public void insertTask(TaskItem taskItem) {
        new InsertTaskAsync(repository).execute(taskItem);
    }
    
    /**
     * 更新任务
     */
    public void updateTask(TaskItem taskItem) {
        new UpdateTaskAsync(repository).execute(taskItem);
    }
    
    /**
     * 删除任务
     */
    public void deleteTask(TaskItem taskItem) {
        new DeleteTaskAsync(repository).execute(taskItem);
    }
    
    // 异步任务类
    private static class InsertTaskAsync extends AsyncTask<TaskItem, Void, Void> {
        private TaskRepository repository;
        
        InsertTaskAsync(TaskRepository repository) {
            this.repository = repository;
        }
        
        @Override
        protected Void doInBackground(TaskItem... taskItems) {
            repository.insert(taskItems[0]);
            return null;
        }
    }
    
    private static class UpdateTaskAsync extends AsyncTask<TaskItem, Void, Void> {
        private TaskRepository repository;
        
        UpdateTaskAsync(TaskRepository repository) {
            this.repository = repository;
        }
        
        @Override
        protected Void doInBackground(TaskItem... taskItems) {
            repository.update(taskItems[0]);
            return null;
        }
    }
    
    private static class DeleteTaskAsync extends AsyncTask<TaskItem, Void, Void> {
        private TaskRepository repository;
        
        DeleteTaskAsync(TaskRepository repository) {
            this.repository = repository;
        }
        
        @Override
        protected Void doInBackground(TaskItem... taskItems) {
            repository.delete(taskItems[0]);
            return null;
        }
    }
    


    /**
     * 获取已阅事项总数
     */
    public LiveData<Integer> getReadDoneTaskCount(String assigneeId) {
        return repository.getReadDoneTaskCount(assigneeId);
    }

    /**
     * 创建新任务
     */
    public void createTask(String title, String content, String taskType, String status,
                          String priority, Date deadline, String creatorId, String assigneeId) {
        isLoading.setValue(true);
        errorMessage.setValue(null);

        try {
            TaskItem task = new TaskItem();
            task.setTitle(title);
            task.setContent(content);
            task.setTaskType(taskType);
            task.setStatus(status);
            task.setPriority(priority);
            task.setDeadline(deadline);
            task.setCreatorId(creatorId);
            task.setAssigneeId(assigneeId);
            task.setCreateTime(new Date());

            repository.insert(task);
        } catch (Exception e) {
            errorMessage.setValue("创建任务失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            isLoading.setValue(false);
        }
    }

    /**
     * 更新任务状态
     */
    public void updateTaskStatus(int taskId, String status) {
        isLoading.setValue(true);
        errorMessage.setValue(null);

        try {
            TaskItem task = repository.getTaskByIdSync(taskId);
            if (task != null) {
                task.setStatus(status);
                if ("已完成".equals(status)) {
                    task.setCompletionTime(new Date());
                }
                repository.update(task);
            } else {
                errorMessage.setValue("未找到任务记录，无法更新");
            }
        } catch (Exception e) {
            errorMessage.setValue("更新任务状态失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            isLoading.setValue(false);
        }
    }

    /**
     * 更新任务优先级
     */
    public void updateTaskPriority(int taskId, String priority) {
        isLoading.setValue(true);
        errorMessage.setValue(null);

        try {
            TaskItem task = repository.getTaskByIdSync(taskId);
            if (task != null) {
                task.setPriority(priority);
                repository.update(task);
            } else {
                errorMessage.setValue("未找到任务记录，无法更新");
            }
        } catch (Exception e) {
            errorMessage.setValue("更新任务优先级失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            isLoading.setValue(false);
        }
    }

    /**
     * 获取加载状态
     */
    public LiveData<Boolean> getIsLoading() {
        return isLoading;
    }

    /**
     * 获取错误信息
     */
    public LiveData<String> getErrorMessage() {
        return errorMessage;
    }
}